﻿#include "MainWindow.h"
#include "SoftwareRegisterDialog.h"

#include <QDebug>
#include <QMessageBox>

namespace Core {

	MainWindow::MainWindow(QWidget *parent)
		: QMainWindow(parent)
		, m_pRegistrationAlgorithm(nullptr)
	{
		ui.setupUi(this);
		this->setWindowTitle(u8"软件注册机");
	}

	MainWindow::~MainWindow()
	{
		if (m_pRegistrationAlgorithm != nullptr)
		{
			delete m_pRegistrationAlgorithm;
			m_pRegistrationAlgorithm = nullptr;
		}
	}

	void MainWindow::initAll()
	{
		initMenu();
		initWidget();

		m_pRegistrationAlgorithm = new RegistrationAlgorithm(this);

		connect(ui.pushButton_register, &QPushButton::clicked, this, &MainWindow::slotCreateRegisterCodeBtnClicked);
		connect(ui.checkBox_forver, &QCheckBox::clicked, this, &MainWindow::slotForverCheckBoxClicked);
	}

	void MainWindow::slotRegisterActionTriggered()
	{
		SoftwareRegisterDialog dialog(this);
		dialog.exec();
	}

	void MainWindow::slotCreateRegisterCodeBtnClicked()
	{
		if (ui.lineEdit_machineCode->text().isEmpty())
		{
			QMessageBox::warning(nullptr, u8"提示", u8"输入的机器码为空，请认真填写信息!!!!");
			return;
		}

		QString strMachineCode = ui.lineEdit_machineCode->text();
		
		QString strRegistrationEndData;
		if (ui.checkBox_forver->isChecked())
		{
			strRegistrationEndData = QDate::currentDate().addYears(500).toString("yyyy-MM-dd");

			QMessageBox::StandardButton result = QMessageBox::warning(nullptr, u8"提示", u8"软件是否永久激活???", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
			if (QMessageBox::No == result)
			{
				return;
			}
		}
		else
		{
			strRegistrationEndData = ui.dateEdit->date().toString("yyyy-MM-dd");

			QMessageBox::StandardButton result = QMessageBox::warning(nullptr, u8"提示", QString(u8"软件是否激活到 %1 ").arg(strRegistrationEndData), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
			if (QMessageBox::No == result)
			{
				return;
			}
		}

		QString strRegistrationCode = m_pRegistrationAlgorithm->generateRegistrationCode(strRegistrationEndData, strMachineCode);

		if (!strRegistrationCode.isEmpty())
		{
			ui.textEdit_registrationCode->setText(strRegistrationCode);
		}

		QMessageBox::warning(nullptr, u8"提示", strRegistrationCode.isEmpty() ? u8"生成注册码失败!!!" : u8"生成注册码成功。。。", QMessageBox::Yes);
	}

	void MainWindow::slotForverCheckBoxClicked(bool checked)
	{
		ui.dateEdit->setEnabled(!checked);
	}

	void MainWindow::initMenu()
	{
		m_pMenuTest = new QMenu(u8"调试", this);

		m_pActionRegister = new QAction(u8"注册", this);
		connect(m_pActionRegister, &QAction::triggered, this, &MainWindow::slotRegisterActionTriggered);
		m_pMenuTest->addAction(m_pActionRegister);

		m_pMenuHelp = new QMenu(u8"帮助", this);

		ui.menuBar->addMenu(m_pMenuTest);
		ui.menuBar->addMenu(m_pMenuHelp);
	}

	void MainWindow::initWidget()
	{
		ui.dateEdit->setDateTime(QDateTime::currentDateTime().addDays(7));
	}

}//namespace Core 